import axios from "axios";
import jsBridge from "../jsBridge/jsBridge";
import Vue from "vue";

const u = navigator.userAgent;
const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1;

/**
 * the request prefix
 */
// const prefix = '/local/'
const prefix = "";

const request = axios.create({
  baseURL: prefix,
  headers: {
    "Content-Type": "application/json;charset=utf-8"
  },
  withCredentials: true,
  params: {}
});

request.interceptors.request.use(
  config => {
    return config;
  },
  error => {
    console.log("error", error);
    return Promise.reject(new Error(error).message);
  }
);

request.interceptors.response.use(
  response => {
    console.info(response.data.data);
    return response.data;
  },
  error => {
    console.log("error", error);
    return Promise.reject(new Error(error).message);
  }
);

export default request;

/**
 * 发送请求
 * */
export function $remote(url, params, type) {
  return new Promise(resolve => {
    type = type || "post";
    if (this.$setClientMode) {
      let proxyParams = {
        TradeCode: url,
        Param: JSON.stringify(params)
      };
      if (type === "get") {
        jsBridge.callhandler("getH5RequestProxy", proxyParams, data => {
          result(data, resolve);
        });
      } else {
        jsBridge.callhandler("H5RequestProxy", proxyParams, data => {
          /**
           * 安卓：以object的string形式传送数据，需要做转义操作
           * ios：以object形式传送数据，不需要做转义操作
           * */
          if (isAndroid) {
            data = JSON.parse(data);
            result(data, resolve);
          } else {
            result(data, resolve);
          }
        });
      }
    } else {
      request[type](url, params).then(data => {
        result(data, resolve);
      });
    }
  });
}

function result(data, resolve) {
  if (data) {
    if (data.status === "000000") {
      resolve(data.data);
    } else {
      alert(data.msg);
    }
  }
}

/**
 * 发送请求方法
 * */
Vue.prototype.$remote = $remote;
window.$remote = $remote;
